package top.v5it.japi.plus.common.func;

import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * 自定义函数接口
 *
 * @author zhanpu
 * @date 2018/12/18
 */
@FunctionalInterface
public interface Func2<T, U, R, E extends Throwable> {

    /**
     * Applies this function to the given arguments.
     *
     * @param t the first function argument
     * @param u the second function argument
     * @return the function result
     * @throws E
     */
    R apply(T t, U u) throws E;

    /**
     * 处理往外抛异常
     *
     * @param after
     * @param <V>
     * @return
     */
    default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);

        return (t, u) -> {
            try {
                return after.apply(apply(t, u));
            } catch (Throwable e) {
                throw new FuncException(e);
            }
        };
    }

    /**
     * 基于本函数返回{@link FuncException}
     *
     * @param t 参数t
     * @param u 参数u
     * @return R 返回值
     */
    default R applyWithFuncException(T t, U u) {
        try {
            return apply(t, u);
        } catch (Throwable e) {
            throw new FuncException(e);
        }
    }
}
